using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.PlayerLoop;

public class Broad : MonoBehaviour
{
    public int width;
    public int height;

    public GameObject tilePrefab;
    private TileBackgroud[,] tileGrids;

    public GameObject[,] AllDots;

    public GameObject[] tiles;

    // Start is called before the first frame update
    void Start()
    {
        tileGrids = new TileBackgroud[width, height];
        AllDots = new GameObject[width, height];
        SetUp();
    }

    public void SetUp()
    {
        for (var i = 0; i < width; i++)
        {
            for (var j = 0; j < height; j++)
            {
                var vector2 = new Vector2(i, j);
                var gb = Instantiate(tilePrefab, vector2, Quaternion.identity) as GameObject;
                gb.transform.SetParent(transform);
                gb.name = "[" + i + "_" + j + "]";
                tileGrids[i, j] = gb.GetComponent<TileBackgroud>();

                var random = Random.Range(0, tiles.Length);
                var count = 0;
                var dot = tiles[random];
                while (count < 100)
                {
                    if (!CheckMatch(i, j, dot.GetComponent<Dot>())) break;
                    random = Random.Range(0, tiles.Length);
                    dot = tiles[random];
                    count++;
                    Debug.Log("count: " + count);
                }

                var tile = Instantiate(dot, gb.transform.position, Quaternion.identity);
                tile.transform.SetParent(gb.transform);
                tile.name = "[" + i + "_" + j + "]";
                AllDots[i, j] = tile;
            }
        }
    }

    private bool CheckMatch(int row, int column, Dot dot)
    {
        if (row > 1 && column > 1)
        {
            if (AllDots[row, column - 1].CompareTag(dot.tag) && AllDots[row, column - 2].CompareTag(dot.tag))
            {
                return true;
            }

            if (AllDots[row - 1, column].CompareTag(dot.tag) && AllDots[row - 2, column].CompareTag(dot.tag))
            {
                return true;
            }
        }
        else if (row > 1 || column > 1)
        {
            if (row > 1)
            {
                if (AllDots[row - 1, column].CompareTag(dot.tag) && AllDots[row - 2, column].CompareTag(dot.tag))
                {
                    return true;
                }
            }
            else if (column > 1)
            {
                if (AllDots[row, column - 1].CompareTag(dot.tag) && AllDots[row, column - 2].CompareTag(dot.tag))
                {
                    return true;
                }
            }
        }


        return false;
    }

    private void DestroyMatch(int column, int row)
    {
        if (AllDots[column, row] == null || !AllDots[column, row].GetComponent<Dot>().isMatch) return;
        Destroy(AllDots[column, row]);
        AllDots[column, row] = null;
    }


    public void DestroyMatches()
    {
        for (var i = 0; i < width; i++)
        {
            for (var j = 0; j < height; j++)
            {
                DestroyMatch(i, j);
            }
        }

        StartCoroutine(DecreaseRowCo());
    }

    public IEnumerator DecreaseRowCo()
    {
        for (var i = 0; i < width; i++)
        {
            var nullCount = 0;
            for (var j = 0; j < height; j++)
            {
                if (AllDots[i, j] == null)
                {
                    nullCount++;
                }
                else if (nullCount > 0)
                {
                    AllDots[i, j].GetComponent<Dot>().row -= nullCount;
                    AllDots[i, j] = null;
                }
            }
        }

        yield return new WaitForSeconds(0.4f);
        StartCoroutine(FillBroadCo());
    }

    private void RefillBord()
    {
        for (var i = 0; i < width; i++)
        {
            for (var j = 0; j < height; j++)
            {
                if (AllDots[i, j] != null) continue;
                var random = Random.Range(0, tiles.Length);
                var tile = Instantiate(tiles[random], new Vector2(i, j), Quaternion.identity);
                tile.transform.SetParent(transform);
                tile.name = "[" + i + "_" + j + "]";
                AllDots[i, j] = tile;
            }
        }
    }

    private IEnumerator FillBroadCo()
    {
        RefillBord();
        
        yield return new WaitForSeconds(0.5f);
        while (CheckMatchesOnBoard())
        {
            yield return new WaitForSeconds(0.5f);
            DestroyMatches();
        }
    }

    private bool CheckMatchesOnBoard()
    {
        for (var i = 0; i < width; i++)
        {
            for (var j = 0; j < height; j++)
            {
                if (AllDots[i, j] != null && AllDots[i, j].GetComponent<Dot>().isMatch)
                {
                    return true;
                }
            }
        }

        return false;
    }


    // Update is called once per frame
    void Update()
    {
    }
}